import { FC, useEffect, useRef, useState } from "react"
import Taro from '@tarojs/taro'
import { tagListObj, GoodsInfo } from './hook/usePageEffect'
import { Button, Picker } from "@tarojs/components"
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import map from '@/resource/map.png'
import TagListPick from '../../TagListPick'
import style from './style.less'

const Common: FC = () => {
  const [carLength, setCarLength] = useState('')
  const [carType, setCarType] = useState('')
  const [tagListPickVisible, setTagListPickVisible] = useState(false)
  const [isShow, setIsShow] = useState(false)
  const source = useRef<HTMLInputElement>(null)
  const source2 = useRef<HTMLInputElement>(null)
  const target = useRef<HTMLInputElement>(null)
  const target2 = useRef<HTMLInputElement>(null)
  const info = useRef<HTMLInputElement>(null)
  const info2 = useRef<HTMLInputElement>(null)
  const weight = useRef<HTMLInputElement>(null)
  const volume = useRef<HTMLInputElement>(null)
  const car = useRef<HTMLInputElement>(null)
  const date = useRef<HTMLInputElement>(null)
  const time = useRef<HTMLInputElement>(null)
  const date2 = useRef<HTMLInputElement>(null)
  const time2 = useRef<HTMLInputElement>(null)

  const [multiArray, setMultiArray] = useState<string[][]>([['金属钢材', '鲜活水产', '煤炭矿产', '瓜果蔬菜', '木头材料'], ['钢管金属管', '铝制材料', '角钢槽钢', '金属工业原料'], ['裸装', '木箱', '托盘', '捆扎', '架子', '其他']])
  const [multiIndex, setMultiIndex] = useState<number[]>([0, 0, 0])

  useEffect(() => {
    if (Taro.getStorageSync('res')) {
      const res = JSON.parse(Taro.getStorageSync('res'))
      console.log('保存的数据', res);

      source.current!.value = res.loadAddress.split(' ')[0]
      source2.current!.value = res.loadAddress.split(' ')[1]
      target.current!.value = res.unloadingAdress.split(' ')[0]
      target2.current!.value = res.unloadingAdress.split(' ')[1]
      info.current!.value = res.cargoName + ' ' + res.packingType
      goodsInfo.current.cargoName = res.cargoName
      goodsInfo.current.packingType = res.packingType
      info2.current!.value = res.truckWeight + '吨 ' + res.cargoCapacipy + '立方米'
      goodsInfo.current.truckWeight = Number(res.truckWeight)
      goodsInfo.current.cargoCapacipy = Number(res.cargoCapacipy)
      weight.current!.value = res.truckWeight
      volume.current!.value = res.cargoCapacipy
      car.current!.value = res.truckLength + '米 ' + res.truckType
      goodsInfo.current.truckLength = res.truckLength
      goodsInfo.current.truckType = res.truckType
      date.current!.value = res.loadTime.split(' ')[0]
      time.current!.value = res.loadTime.split(' ')[1]
      date2.current!.value = res.unloadingTime.split(' ')[0]
      time2.current!.value = res.unloadingTime.split(' ')[1]
      goodsInfo.current.loadLatitude = res.loadLatitude
      goodsInfo.current.loadLongitude = res.loadLongitude
      goodsInfo.current.unloadLatitude = res.unloadLatitude
      goodsInfo.current.unloadLongitude = res.unloadLongitude
    }
  }, [])

  const choosePosition = (num) => {
    Taro.chooseLocation({
      success: (res) => {
        console.log('坐标值', res);
        console.log(typeof res.latitude);

        if (num === 1) {
          source2.current!.value = res.name
          goodsInfo.current.loadLatitude = res.latitude
          console.log(typeof goodsInfo.current.loadLatitude);

          goodsInfo.current.loadLongitude = res.longitude
          return
        }
        if (num === 2) {
          target2.current!.value = res.name
          goodsInfo.current.unloadLatitude = res.latitude
          goodsInfo.current.unloadLongitude = res.longitude
          return
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })
  }

  const goodsInfo = useRef<GoodsInfo>({
    loadLinkman: '',
    loadTime: '',
    truckType: '',
    openId: Taro.getStorageSync('token'),
    cargoFee: 0,
    loadAddress: '',
    truckWeight: 0,
    remark: '',
    unloadingAdress: '',
    unloadingLinkman: '',
    packingType: '',
    cargoCapacipy: 0,
    unloadingTime: '',
    deposit: 0,
    truckLength: '',
    needReturnDeposit: 0,
    cargoName: '',
    loadLatitude: '',
    loadLongitude: '',
    unloadLatitude: '',
    unloadLongitude: '',
  })

  const getDate = () => {
    var time = new Date();
    var year = time.getFullYear()  //年
    var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
    var day = ("0" + time.getDate()).slice(-2); //日
    var mydate = year + "-" + month + "-" + day;
    return mydate
  }

  const handleTagListPickConfirm = (pickedTags: arrObject) => {
    let [carLenthPicked, carTypesPicked] = [
      pickedTags['车长'],
      pickedTags['车型'],
    ];

    if (carLenthPicked[0] && carTypesPicked[0]) {
      setTagListPickVisible(false)
      car.current!.value = carLenthPicked[0] + '米 ' + carTypesPicked[0]
      goodsInfo.current.truckLength = carLenthPicked[0]
      goodsInfo.current.truckType = carTypesPicked[0]
    } else {
      Taro.showToast({
        title: '请选择',
        icon: 'none',
        duration: 1500
      })
    }

    carLenthPicked.length && setCarLength(`车长: ${carLenthPicked[0]}`)
    carTypesPicked.length && setCarType(`车型: ${carTypesPicked[0]}`)
  }

  const next = () => {
    if (source.current?.value && source2.current?.value && target.current?.value &&
      target2.current?.value && info.current?.value && info2.current?.value &&
      car.current?.value && date.current?.value && time.current?.value &&
      date2.current?.value && time2.current?.value
    ) {
      goodsInfo.current.loadAddress = source.current.value + ' ' + source2.current.value
      goodsInfo.current.unloadingAdress = target.current.value + ' ' + target2.current.value
      goodsInfo.current.loadTime = date.current.value + ' ' + time.current.value
      goodsInfo.current.unloadingTime = date2.current.value + ' ' + time2.current.value

      const res = JSON.stringify(goodsInfo.current)
      Taro.setStorageSync('res', res)

      Taro.navigateTo({ url: `/packageB/deliver/waybill/index?res=${res}` })
    } else {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
        duration: 1500
      })
    }
  }

  const changeRegion = (e, num) => {
    if (num === 0) {
      source.current!.value = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
    } else if (num === 1) {
      target.current!.value = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
    } else if (num === 2) {
      if (date2.current!.value === '') {
        date.current!.value = e.detail.value
        return
      }
      if (e.detail.value > date2.current!.value) {
        Taro.showToast({
          title: '装货时间不能在卸货时间之后',
          icon: 'none',
          duration: 2000
        })
      } else {
        date.current!.value = e.detail.value
      }
    } else if (num === 3) {
      time.current!.value = e.detail.value
    } else if (num === 4) {
      if (date.current!.value === '') {
        date2.current!.value = e.detail.value
        return
      }
      if (date.current!.value > e.detail.value) {
        Taro.showToast({
          title: '卸货时间不能在装货时间之前',
          icon: 'none',
          duration: 2000
        })
      } else {
        date2.current!.value = e.detail.value
      }
    } else if (num === 5) {
      time2.current!.value = e.detail.value
    }
  }

  const bindMultiPickerChange = (e) => {
    info.current!.value = multiArray[1][e.detail.value[1]] + ' ' + multiArray[2][e.detail.value[2]]
    goodsInfo.current.cargoName = multiArray[1][e.detail.value[1]]
    goodsInfo.current.packingType = multiArray[2][e.detail.value[2]]

  }

  const bindMultiPickerColumnChange = (e) => {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      // multiArray: [[...multiArray[0]], [...multiArray[1]]],
      multiArray: [...multiArray],
      multiIndex: [...multiIndex]
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        // ['金属钢材', '鲜活水产', '煤炭矿产']
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = ['钢管金属管', '铝制材料', '角钢槽钢', '金属工业原料'];
            data.multiArray[2] = ['裸装', '木箱', '托盘', '捆扎', '架子', '其他'];
            break;
          case 1:
            data.multiArray[1] = ['活鱼', '活虾', '活蟹', '海鲜海产品'];
            data.multiArray[2] = ['水箱', '其他'];
            break;
          case 2:
            data.multiArray[1] = ['矿粉矿渣', '煤炭'];
            data.multiArray[2] = ['吨包', '袋装', '托盘', '散装', '其他'];
            break;
          case 3:
            data.multiArray[1] = ['叶菜', '根菜', '葱蒜', '薯芋', '瓜类', '豆类', '新鲜菌菇'];
            data.multiArray[2] = ['袋装', '筐装', '散装', '纸箱', '其他'];
            break;
          case 4:
            data.multiArray[1] = ['花草', '木材', '木方方料', '木板'];
            data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
            break;
        }
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        break;
      case 1:
        switch (data.multiIndex[0]) {
          case 0:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['裸装', '木箱', '托盘', '捆扎', '架子', '其他'];
                break;
              case 1:
                data.multiArray[2] = ['裸装', '木箱', '托盘', '压块', '架子', '其他'];
                break;
              case 2:
                data.multiArray[2] = ['裸装', '托盘', '捆扎', '其他'];
                break;
              case 3:
                data.multiArray[2] = ['吨包', '袋装', '托盘', '木箱', '桶装', '其他'];
                break;
            }
            break;
          case 1:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['水箱', '其他'];
                break;
              case 1:
                data.multiArray[2] = ['泡沫箱', '水箱', '其他'];
                break;
              case 2:
                data.multiArray[2] = ['泡沫箱', '其他'];
                break;
              case 3:
                data.multiArray[2] = ['水箱', '袋装', '其他'];
                break;
            }
            break;
          case 2:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['吨装', '袋装', '托盘', '散装', '其他'];
                break;
              case 1:
                data.multiArray[2] = ['吨装', '袋装', '托盘', '散装', '其他'];
                break;
            }
            break;
          case 3:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['袋装', '筐装', '散装', '纸箱', '其他'];
                break;
              case 1:
                data.multiArray[2] = ['散装', '筐装', '袋装', '纸箱', '其他'];
                break;
              case 2:
                data.multiArray[2] = ['袋装', '纸箱', '散装', '筐装', '其他'];
                break;
              case 3:
                data.multiArray[2] = ['纸箱', '筐装', '散装', '袋装', '其他'];
                break;
              case 4:
                data.multiArray[2] = ['袋装', '散装', '筐装', '纸箱', '其他'];
                break;
              case 5:
                data.multiArray[2] = ['筐装', '袋装', '散装', '纸箱', '其他'];
                break;
              case 6:
                data.multiArray[2] = ['袋装', '筐装', '纸箱', '散装', '其他'];
                break;
            }
            break;
          case 4:
            switch (data.multiIndex[1]) {
              case 0:
                data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
                break;
              case 1:
                data.multiArray[2] = ['散装', '木箱', '裸装', '袋装', '其他'];
                break;
              case 2:
                data.multiArray[2] = ['裸装', '捆扎', '散装', '袋装', '其他'];
                break;
              case 3:
                data.multiArray[2] = ['袋装', '捆扎', '散装', '裸装', '其他'];
                break;
            }
            break;
        }
        data.multiIndex[2] = 0;
        console.log(data.multiIndex);
        break;
    }
    console.log(data.multiArray, data.multiIndex);

    setMultiArray(data.multiArray)
    setMultiIndex(data.multiIndex)
  }

  const showInfo = () => {
    if (weight.current?.value && volume.current?.value) {
      info2.current!.value = ` ${weight.current.value}吨 ${volume.current.value}立方米`
      goodsInfo.current.truckWeight = Number(weight.current.value)
      goodsInfo.current.cargoCapacipy = Number(volume.current.value)
      setIsShow(false)
    } else {
      Taro.showToast({
        title: '请填写',
        icon: 'none',
        duration: 1500
      })
    }
  }

  return (
    <div className={style.root}>
      <div className="address">
        <div className="zhuang" >装</div>
        <Picker mode='region' value={['江苏省', '南京市', '雨花台区']} onChange={(e) => { changeRegion(e, 0) }}>
          <input ref={source} type="text" placeholder="省、市、区" disabled className="input" />
        </Picker>
        <div className="position" onClick={() => { choosePosition(1) }}>
          <input ref={source2} type="text" disabled placeholder="请选择具体装货地址" />
          <img src={map} alt="" />
        </div>
        <div className="line" />
        <div className="xie">卸</div>
        <Picker mode='region' value={['北京市', '北京市', '朝阳区']} onChange={(e) => { changeRegion(e, 1) }}>
          <input ref={target} type="text" placeholder="省、市、区" disabled className="input" />
        </Picker>
        <div className="position" onClick={() => { choosePosition(2) }}>
          <input ref={target2} type="text" disabled placeholder="请选择具体卸货地址" />
          <img src={map} alt="" />
        </div>
      </div>
      <Picker mode='multiSelector' range={multiArray} value={multiIndex} onChange={bindMultiPickerChange} onColumnChange={bindMultiPickerColumnChange}>
        <div className="info">
          <div>货物信息:</div>
          <input ref={info} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <div className="info" onClick={() => { setIsShow(true) }}>
        <div>重量体积:</div>
        <input ref={info2} type="text" placeholder=">" disabled />
      </div>
      <div className="info" onClick={() => { setTagListPickVisible(true) }}>
        <div>车长车型:</div>
        <input ref={car} type="text" placeholder=">" disabled />
      </div>
      <Picker mode='date' value="" start={getDate()} onChange={(e) => { changeRegion(e, 2) }}>
        <div className="info">
          <div>装货日期:</div>
          <input ref={date} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='time' value="12:01" onChange={(e) => { changeRegion(e, 3) }}>
        <div className="info">
          <div>装货时间:</div>
          <input ref={time} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='date' value="" start={getDate()} onChange={(e) => { changeRegion(e, 4) }}>
        <div className="info">
          <div>卸货日期:</div>
          <input ref={date2} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <Picker mode='time' value="12:01" onChange={(e) => { changeRegion(e, 5) }}>
        <div className="info">
          <div>卸货时间:</div>
          <input ref={time2} type="text" placeholder=">" disabled />
        </div>
      </Picker>
      <div className="next" onClick={next}>下一步</div>

      <TagListPick
        title="车长车型"
        visible={tagListPickVisible}
        tagListObj={tagListObj}
        cancleCallback={() => { setTagListPickVisible(false) }}
        confirmCallback={handleTagListPickConfirm}
      />

      <AtModal isOpened={isShow} closeOnClickOverlay={false}>
        <AtModalHeader>重量/体积</AtModalHeader>
        <AtModalContent>
          <div className="size">
            <div>重量</div>
            <input ref={weight} type="number" />
            <div>吨</div>
          </div>
          <div className="size">
            <div>体积</div>
            <input ref={volume} type="number" />
            <div>立方米</div>
          </div>
        </AtModalContent>
        <AtModalAction> <Button onClick={() => { setIsShow(false) }}>取消</Button> <Button onClick={() => { showInfo() }}>确定</Button> </AtModalAction>
      </AtModal>
    </div >
  )
}

export default Common